//
//  SD_ContactListVC.m
//  GSD_WeiXin(wechat)
//
//  Created by zeng on 2018/3/22.
//  Copyright © 2018年 GSD. All rights reserved.
//

#import "SD_ContactListVC.h"
#import "Zz_ContactListCell.h"
@interface SD_ContactListVC ()<UITableViewDataSource,UITableViewDelegate>
{


        //记录删除联系人电话号码
        NSMutableArray *mobileArray;

        //数据得数据源
        NSMutableArray *dataArray;

        //全选按钮
        UIButton *selectAll;

        //是否全选
        BOOL isSelect;

        //已选的商品合集
        NSMutableArray *selectGoods;
        NSMutableArray *_arrContacts;

}

@property (nonatomic, strong) UILabel *countLable;

@property (nonatomic, strong) NSArray<SYContacter *> *contactsArray;

@property (nonatomic, strong) UIButton *rmButton;
@property (nonatomic, strong) UITableView *contactListTableView;

/**批量删除*/
@property (nonatomic, strong) UIButton *removePeopleBtn;


@property (nonatomic, strong) UIButton *paiPictureBtn;
@end

@implementation SD_ContactListVC
- (void)viewWillAppear:(BOOL)animated
{
    //每次进入通讯录的时候把选择的置空
    [selectGoods removeAllObjects];
    isSelect = NO;
    selectAll.selected = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad]; 

    dataArray = [[NSMutableArray alloc] init];
    selectGoods = [[NSMutableArray alloc] init];
    mobileArray = [[NSMutableArray alloc] init];

    self.navigationItem.title=@"联系人";

    
    self.contactListTableView = [[UITableView alloc] init];
    self.contactListTableView.delegate =self;
    self.contactListTableView.dataSource = self;
    self.contactListTableView.showsVerticalScrollIndicator = NO;
    //self.contactListTableView.separatorStyle = 0;
    self.contactListTableView.rowHeight = 50;
    self.contactListTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.contactListTableView];
    [self.contactListTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.and.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-100);
    }];



    _paiPictureBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _paiPictureBtn.backgroundColor=XMGRGBColor(0, 222, 22);
    _paiPictureBtn.layer.cornerRadius=5.0;
    _paiPictureBtn.layer.masksToBounds=YES;
    [_paiPictureBtn setTitle:@"上传联系人" forState:UIControlStateNormal];
    [self.view addSubview:_paiPictureBtn];
    [_paiPictureBtn addTarget:self action:@selector(uploadContactPeople) forControlEvents:UIControlEventTouchUpInside];
    [_paiPictureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(30);
        make.width.mas_equalTo((kk_WIDTH-90)/2);
        make.height.mas_equalTo(36);
        make.bottom.mas_equalTo(-54);

    }];
    _removePeopleBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    _removePeopleBtn.backgroundColor=XMGRGBColor(0, 222, 22);
    _removePeopleBtn.layer.cornerRadius=5.0;
    _removePeopleBtn.layer.masksToBounds=YES;
    [_removePeopleBtn setTitle:@"批量删除" forState:UIControlStateNormal];
    [self.view addSubview:_removePeopleBtn];
    [_removePeopleBtn addTarget:self action:@selector(deletContactPeople) forControlEvents:UIControlEventTouchUpInside];
    [_removePeopleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-40);
        make.width.mas_equalTo((kk_WIDTH-90)/2);
        make.height.mas_equalTo(36);
        make.bottom.mas_equalTo(-54);

    }];
    // 获取所以联系人
   // [self getContactsAllArray];
    ///下载所有联系人
    [self downLoadContactPeople];

    [self setNav];
    
}

#pragma mark ===下载所有联系人
-(void)downLoadContactPeople{


    NSMutableDictionary *dictM=[NSMutableDictionary dictionary];
    dictM[@"Id"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_messageId"];
    dictM[@"Token"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_token"]; 

    NSLog(@"  dictM！！！===%@",dictM);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 

    [manager POST:[NSString stringWithFormat:@"%@%@",host_api,ListPhoneDetail_api] parameters:dictM progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"下载所有联系人 ！！！===%@",responseObject);
        dataArray=[SD_ContactListPhoneDetail mj_objectArrayWithKeyValuesArray:responseObject[@"RepPhoneItemModels"]];


        [self.contactListTableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


    }];
    
}

#pragma mark ===批量删除联系人
-(void)deletContactPeople{


    for (SD_ContactListPhoneDetail *dict in selectGoods) {


        [mobileArray addObject:dict.MobileCode];
        NSLog(@"批量删除联系人号码: =%@",dict.MobileCode);
    }

    NSMutableDictionary *dictM=[NSMutableDictionary dictionary];

    dictM[@"Id"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_messageId"];
    dictM[@"Token"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_token"];
    dictM[@"MobilePhoneIds"]=mobileArray;

    NSLog(@"  dictM！！！===%@",dictM);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:[NSString stringWithFormat:@"%@%@",host_api,DeletBatch_api] parameters:dictM progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"批量删除联系人成功 ！！！===%@",responseObject);
        [self downLoadContactPeople ];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


    }];
}

#pragma mark ===上传通讯录 联系人
-(void)uploadContactPeople{

    NSMutableDictionary *dictM=[NSMutableDictionary dictionary];
    NSArray *array=@[
                     @{@"MobileCode":@"15000000000",
                       @"Name":@"zengw",
                       @"CommitContent":@"流经岁月"
                       },
                     @{@"MobileCode":@"15443333333",
                       @"Name":@"zengw",
                       @"CommitContent":@"和小九天"
                       },
                     @{@"MobileCode":@"1555550000",
                       @"Name":@"zengw",
                       @"CommitContent":@"倚天屠龙"
                       }
                     ];

    dictM[@"Id"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_messageId"];
    dictM[@"Token"]=[[NSUserDefaults standardUserDefaults]objectForKey:@"user_token"];
    dictM[@"AddMobilePhoneDetails"]=array;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    [manager POST:[NSString stringWithFormat:@"%@%@",host_api,AddMobilePhone_api] parameters:dictM progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功！！！===%@",responseObject);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {


    }];
}

#pragma mark ===获取联系人列表
-(void)getContactsAllArray{
    
    dataArray=[NSMutableArray array];
    [SYContactsHelper fetchContacts:^(NSArray <SYContacter *> *contacts, BOOL success) {
        if (success) {
            
            //[dataArray addObject:contacts];
           // dataArray=contacts;

            if (contacts.count>0) {
                
            }else{ 
                
            }
            
            [self.contactListTableView reloadData];
        }
        else { 
            
        }
    }];
}

#pragma mark -- tableview的代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Zz_ContactListCell *hggCell=[Zz_ContactListCell cellForTableView:tableView];

    hggCell.tag=indexPath.row+10000;

    hggCell.isSelected = isSelect;

    //是否被选中
    if ([selectGoods containsObject:[dataArray objectAtIndex:indexPath.row]])
    {
        hggCell.isSelected = YES;
    }

    //block的实现方法
    hggCell.cartBlock = ^(BOOL isSelec){


        //选中就加入到数组
        if (isSelec) {

            [selectGoods addObject:[dataArray objectAtIndex:indexPath.row]];

            NSLog(@" %zd",selectGoods.count);

            if (selectGoods.count==0) {
                self.navigationItem.title=@"联系人";

            }else{

                self.navigationItem.title=[NSString stringWithFormat:@"联系人(%zd)",selectGoods.count];

            }
        }
        else
        {
            //移除
            [selectGoods removeObject:[dataArray objectAtIndex:indexPath.row]];
            if (selectGoods.count==0) {


                self.navigationItem.title=@"联系人";

            }else{

                self.navigationItem.title=[NSString stringWithFormat:@"联系人(%zd)",selectGoods.count];

            }
        }

        //全选了
        if (selectGoods.count == dataArray.count) {
            selectAll.selected = YES;
        }
        else
        {
            selectAll.selected = NO;
        }

    };
    hggCell.ListPhoneDetailModel=dataArray[indexPath.row];


    return hggCell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@" : commitEditingStyle:indexPath==== %zd ",indexPath.row);


    //SD_ContactListPhoneDetail  *ListPhoneDetailModel=dataArray[indexPath.row];

    [dataArray removeObjectAtIndex:indexPath.row];

    [self.contactListTableView reloadData];


}

#pragma mark -- 全选按钮的点击事件
- (void)selectAllBtnClick:(UIButton *)button
{

    NSInteger cellTag=[button superview].superview.tag;

    NSLog(@"全选按钮的点击事件 的某一行 == %zd。。=%@",cellTag,[button superview].superview);

    //点击全选时，把之前已选择的全部删除
    [selectGoods removeAllObjects];
    button.selected = !button.selected;
    isSelect = button.selected;

    //如果选择了
    if (isSelect) {
        for (SD_ContactListPhoneDetail *model in dataArray) {

            [selectGoods addObject:model];

            self.navigationItem.title=[NSString stringWithFormat:@"联系人(%zd)",selectGoods.count];
        }
    }
    else
    {
        [selectGoods removeAllObjects];


        self.navigationItem.title=@"联系人";
    }

    //刷新
    [self.contactListTableView reloadData];
}
#pragma mark -===== 移除所有/选中的 通讯录
-(void)removeAllContacts:(UIButton *)sender{

    for (SYContacter *tmpPerson in selectGoods) {

        NSString *name=tmpPerson.name;

        ABAddressBookRef tmpAddressBook = ABAddressBookCreate();
        NSArray* tmpPersonArray = (__bridge NSArray*)ABAddressBookCopyArrayOfAllPeople(tmpAddressBook);
        for(id tmpPerson in tmpPersonArray)
        {
            NSString* tmpFirstName = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonFirstNameProperty);
            NSString* tmpLastName  = (__bridge NSString*)ABRecordCopyValue((__bridge ABRecordRef)(tmpPerson), kABPersonLastNameProperty);
            NSString* tmpFullName = [NSString stringWithFormat: @"%@%@", [tmpFirstName lowercaseString], [tmpLastName lowercaseString]];

            //删除联系人

            if([tmpFullName isEqualToString:name]||[tmpFirstName isEqualToString:name]||[tmpLastName isEqualToString:name])
            {
                ABAddressBookRemoveRecord(tmpAddressBook, (__bridge ABRecordRef)(tmpPerson), nil);

            }
        }
        //保存电话本
        ABAddressBookSave(tmpAddressBook, nil);
        //释放内存
        CFRelease(tmpAddressBook);
    }
    self.rmButton.enabled=NO;
    self.rmButton.backgroundColor=[UIColor lightGrayColor];
    [self.rmButton setTitle:[NSString stringWithFormat:@"删除联系人"] forState:UIControlStateNormal];
    isSelect = NO;

    [selectGoods removeAllObjects];
    [self getContactsAllArray];

}

#pragma mark ---配置导航条
- (void)setNav{
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *additionBtn = [[UIButton alloc] init];
    [additionBtn setTitle:@"全选" forState:UIControlStateNormal];
    additionBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [additionBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [additionBtn addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    additionBtn.frame = CGRectMake(0, 0, 40, 25);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:additionBtn];
}


#pragma mark === 显示拒绝信息
- (void)showUserDenied {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    label.textAlignment = NSTextAlignmentCenter;
    label.numberOfLines = 0;
    label.textColor = [UIColor redColor];
    [self.view addSubview:label];

    NSString *str = [NSString stringWithFormat:@"您没有权限访问通讯录\n\n请到“设置-隐私-通讯录”里\n允许”SYContactsPicker“访问"];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:[str rangeOfString:@"您没有权限访问通讯录"]];
    label.attributedText = attributedString;
    [label sizeToFit];
    label.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height);
    label.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2);

    UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settingBtn.frame = CGRectMake(0, 0, 140, 40);
    settingBtn.backgroundColor = [UIColor blueColor];
    settingBtn.layer.cornerRadius = 5;
    settingBtn.layer.masksToBounds = YES;
    [settingBtn setTitle:@"去设置" forState:UIControlStateNormal];
    [settingBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    settingBtn.center = CGPointMake(self.view.frame.size.width / 2, label.center.y + 5 + 20 + label.frame.size.height / 2);
    [settingBtn addTarget:self action:@selector(onClickBtnSetting:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:settingBtn];
}


- (void)onClickBtnSetting:(UIButton *)btn {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root"]];
}

@end
